import { ElMessage } from 'element-plus'
import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/stores/stores.js'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/login',
      component: () => import('@/views/Login.vue')
    },
    {
      path: '/home',
      component: () => import('@/views/Home.vue'),
      children: [
        {
          path: 'administrator/add',
          component: () => import('@/views/AdministratorAdd.vue')
        },
        {
          path: 'administrator/list',
          component: () => import('@/views/AdministratorList.vue')
        },
        {
          path: 'administrator/edit',
          component: () => import('@/views/AdministratorEdit.vue')
        },
        {
          path: 'category/list',
          component: () => import('@/views/CategoryList.vue')
        },
        {
          path: 'article/list',
          component: () => import('@/views/ArticleList.vue')
        },
        {
          path: 'article/add',
          component: () => import('@/views/ArticleAdd.vue')
        },
        {
          path: 'article/edit',
          component: () => import('@/views/ArticleEdit.vue')
        },
        {
          path: 'nav/list',
          component: () => import('@/views/NavList.vue')
        }
      ]
    },
  ]
})

router.beforeEach((to) => {
  const userStore = useUserStore()
  if (to.path === '/login') {
    if (userStore.user.token) {
      return false
    }
  }
  else {
    if (!userStore.user.token) {
      ElMessage({ type: 'info', message: '未登录' })
      return '/login'
    }
    else {
      const dateString = userStore.user.expireDate
      const isoString = dateString.replace(' ', 'T')
      const timestamp = Date.parse(isoString)

      if (Date.now() >= timestamp) {
        ElMessage({ type: 'info', message: '登录过期，重新登录' })
        userStore.deleteUser()
        return '/login'
      }
    }
  }
})

export default router